package yagwl.client.widget.cell;

import com.google.gwt.cell.client.AbstractCell;
import com.google.gwt.cell.client.ValueUpdater;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.resources.client.ImageResource;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.user.client.ui.AbstractImagePrototype;

/**
 * A cell that renders an image and takes a delegate to perform actions on
 * mouseUp.
 * 
 * @param <C>
 *          the type that this Cell represents
 */
public class ImageActionCell<C> extends AbstractCell<C> {

  /**
   * The delegate that will handle events from the cell.
   * 
   * @param <T>
   *          the type that this delegate acts on
   */
  public static interface Delegate<T> {
    /**
     * Perform the desired action on the given object.
     * 
     * @param object
     *          the object to be acted upon
     */
    void execute(T object);
  }

  private final SafeHtml html;
  private final Delegate<C> delegate;

  /**
   * Construct a new {@link ImageActionCell}.
   * 
   * @param imageResource
   *          the image resource to display
   * @param delegate
   *          the delegate that will handle events
   */
  public ImageActionCell(ImageResource imageResource, Delegate<C> delegate) {
    super("click", "keydown");
    this.delegate = delegate;
    if (imageResource != null) {
      this.html = SafeHtmlUtils.fromTrustedString(AbstractImagePrototype
          .create(imageResource).getHTML());
      return;
    }
    this.html = null;
  }

  /*
   * Construct a new {@link ActionCell} with a text String that does not contain
   * HTML markup.
   * 
   * @param text the text to display on the button
   * 
   * @param delegate the delegate that will handle events
   */
  // public ImageActionCell(String text, Delegate<C> delegate) {
  // super("click", "keydown");
  // this.delegate = delegate;
  // this.html = null;
  // this(SafeHtmlUtils.fromString(text), delegate);
  // }

  //@Override
  //public void onBrowserEvent(Element parent, C value, Object key,
  //    NativeEvent event, ValueUpdater<C> valueUpdater) {
  //  super.onBrowserEvent(parent, value, key, event, valueUpdater);
  //  if ("click".equals(event.getType())) {
  //    onEnterKeyDown(parent, value, key, event, valueUpdater);
  //  }
  //}

  //@Override
  //protected void onEnterKeyDown(Element parent, C value, Object key,
  //    NativeEvent event, ValueUpdater<C> valueUpdater) {
  //  delegate.execute(value);
  //}

  // @Override
  // public void render(C value, Object key, SafeHtmlBuilder sb) {
  // sb.append(html);
  // }

  @Override
  public void render(Context context, C value, SafeHtmlBuilder sb) {
    sb.append(html);
  }
}
